import { ref } from "vue"
import JSZip from 'jszip'
import axios from "axios";
import { readLocalJSON } from "@/utils/tools.js"
import { importJSON } from "@/api/library.js"
import { ElMessage,ElLoading } from 'element-plus';
export function useImport(getResource) {

    const JSONfileList = ref([]);
    const uploadFileList = ref([]);
    const fileListCon=ref([])
    const disabledBtn = ref(true)
    const zipFileLoad=ref(false)

    const handleImport = () => {
    }
    const JSONuploadChange = (file, fileList) => {
        console.log(file, fileList);
    }
    const handleUpload = async () => {
        let { raw: file } = JSONfileList.value[0];
        if (file) {
            let res = await readLocalJSON(file);
            const encoder = new TextEncoder();
            const encodedData = encoder.encode(res);
            const originalJSONarr = JSON.parse(sessionStorage.getItem("originalJSONarr") || "[]");
            sessionStorage.setItem("originalJSONarr", JSON.stringify([...originalJSONarr, JSON.parse(res)]));

            const base64Data = btoa(String.fromCharCode.apply(null, encodedData));
            let result = await importJSON({ jsonstr: base64Data });
            const importJSONarrs = JSON.parse(sessionStorage.getItem("importJSONarrs") || "[]");
            sessionStorage.setItem("importJSONarrs", JSON.stringify([...importJSONarrs, result]));
            JSONfileList.value = [];
            getResource();

        } else {
            ElMessage({
                message: '未选择任何文件无法解析',
                type: 'warning',
            })
        }

    }

 //  解析压缩包

 const handleChange = (resFile) => {
    disabledBtn.value = true;
    let { raw: file } = resFile;
    if (file) {
        const reader = new FileReader();
       zipFileLoad.value=true
        reader.onload = async (e) => {
            const arrayBuffer = e.target.result;
            JSZip.loadAsync(arrayBuffer).then((zip) => {
                const fileNames = Object.keys(zip.files);
                const fileList = fileNames.map(async (fileName) => {
                    const content = await zip.files[fileName].async('arraybuffer');
                    const blob = new Blob([content]);
                    const file = new File([blob], fileName, { type: fileType(fileName) });
                    return file;
                });

                Promise.all(fileList).then(files => {
                    
                    // 使用展开运算符将新文件追加到现有列表中
                    uploadFileList.value = [...uploadFileList.value, ...files].filter(file => !file.name.endsWith('.zip'));
                    console.log( uploadFileList.value.length);
                    
                    disabledBtn.value = false;
                    zipFileLoad.value=false
                }).catch(error => {
                    console.error('Error while processing files:', error);
                    disabledBtn.value = false;
                    zipFileLoad.value=false
                });
            }).catch(error => {
                console.error('Error while loading ZIP:', error);
                disabledBtn.value = false;
                zipFileLoad.value=false
            });
        };
        reader.readAsArrayBuffer(file);
       
    }
};

    return {
        handleImport,
        JSONuploadChange,
        JSONfileList,
        uploadFileList,
        handleUpload,
        handleChange,
        disabledBtn,
        zipFileLoad
    }


}

//关于分页的操作
export function usePagination(options, getResource) {
    const pageTotal = ref(0);
    const currentChange = (e) => {
        options.value.page_num = e;
        getResource();
    }
    return {
        currentChange,
        pageTotal
    }
}


// 确定文件类型的方法

const fileType = (fileName) => {

    // 确定file类型
    if (fileName.endsWith('.jpg') || fileName.endsWith('.jpeg')) {
        return 'image/jpeg';
    } else if (fileName.endsWith('.png')) {
        return 'image/png';
    } else if (fileName.endsWith('.gif')) {
        return 'image/gif';
    } else if (fileName.endsWith('.webp')) {
        return 'image/webp';
    } else if (fileName.endsWith('.mp4')) {
        return 'video/mp4';
    } else if (fileName.endsWith('.zip')) {
        return 'application/zip';
    } else if (fileName.endsWith('.rar')) {
        return 'application/rar';
    } else if (fileName.endsWith('.pdf')) {
        return 'application/pdf';
    }
    else {
        // 可以添加更多条件判断其他类型的文件
        return 'application/octet-stream'; // 默认未知类型
    }
}